<template>
	<view class="page-wrap">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill" />
		<u-navbar title="新增电子通知" :autoBack="true" bgColor="transparent" :titleStyle="{ color: '#fff' }" safeAreaInsetTop
			placeholder leftIconColor="#fff" />
		<view class="form-scroll" style="margin-top: 20rpx;">
			<view class="form-card">
				<view class="fc-title">基础信息</view>
				<view class="form-item">
					<text class="label">标题</text>
					<u--input v-model="form.title" placeholder="请输入标题" border="surround" />
				</view>
				<view class="form-item">
					<text class="label">通知类型</text>
					<view class="picker-field" @click="showTypePicker = true">
						<text>{{ getNoticeTypeLabel(form.noticeType) || '请选择' }}</text>
						<u-icon name="arrow-down" size="18" color="#666" />
					</view>
				</view>
				<view class="form-item">
					<text class="label">紧急程度</text>
					<view class="picker-field" @click="showUrgencyPicker = true">
						<text>{{ getUrgencyLabel(form.emergencyLevel) || '请选择' }}</text>
						<u-icon name="arrow-down" size="18" color="#666" />
					</view>
				</view>
				<view class="form-item">
					<text class="label">需回复</text>
					<u-switch v-model="form.needReply" activeValue="Y" inactiveValue="N" size="20" activeColor="#0A993B"
						inactiveColor="#d8d8d8" />
				</view>
				<view class="form-item">
					<text class="label">正文</text>
					<u--textarea v-model="form.content" placeholder="请输入正文" height="220" count />
				</view>
			</view>

			<view class="form-card">
				<view class="fc-title">接收人</view>
				<view class="receiver-box">
					<u-empty v-if="!form.recipientNames" mode="data" text="未选择" icon="data" />
					<view v-else class="tag-list">
						<view v-for="(r, i) in form.recipientNames.split(',')" :key="i" class="tag">{{ r }}</view>
					</view>
					<u-button size="small" type="primary" plain @click="chooseReceivers">选择接收人</u-button>
				</view>
			</view>

			<view class="form-card">
				<view class="fc-title">附件</view>
				<view class="form-item no-flex">
					<u-button size="small" type="primary" @click="handleUpload">上传附件</u-button>
					<text v-if="uploadedFiles.length === 0" class="hint">未选择文件</text>
				</view>
				<view class="upload-list" v-if="uploadedFiles.length > 0">
					<view class="upload-item" v-for="(file, index) in uploadedFiles" :key="index">
						<view class="u-left">
							<u-icon name="file-text" size="26" color="#0A993B" />
							<text class="u-name">{{ file.name }}</text>
							<text class="u-size">{{ formatFileSize(file.size) }}</text>
						</view>
						<view class="u-right">
							<text v-if="file.status === 'success'" class="ok">已上传</text>
							<text v-else-if="file.status === 'progress'" class="ing">{{ file.progress || 0 }}%</text>
							<text v-else-if="file.status === 'fail'" class="fail">失败</text>
							<u-icon name="close" size="22" color="#999" @click="removeFile(index)" />
						</view>
					</view>
				</view>
			</view>

			<view class="bottom-space" />
		</view>

		<view class="btn-bar safe-area-inset-bottom">
			<u-button type="primary" color="#0A993B" @click="onPublish">{{ showbutt ? '修改' : '发布' }}</u-button>
			<!-- <u-button v-if="!showbutt" type="success" plain @click="onSaveDraft">存草稿</u-button> -->
			<u-button type="warning" plain @click="onReset">重置</u-button>
		</view>

		<u-picker :show="showTypePicker" :columns="[noticeTypeOptions.map(i => i.label)]" @confirm="onTypeConfirm"
			@cancel="showTypePicker = false" @close="showTypePicker = false" />
		<u-picker :show="showUrgencyPicker" :columns="[urgencyOptions.map(i => i.label)]" @confirm="onUrgencyConfirm"
			@cancel="showUrgencyPicker = false" @close="showUrgencyPicker = false" />
		<lsj-upload ref="lsjUploadRef"></lsj-upload>

		<!-- 接收人选择弹窗 -->
		<u-popup :show="showReceiverPicker" mode="bottom" :round="18" @close="closeReceiverPopup">
			<view class="receiver-popup-simple">
				<view class="rps-hd">
					<text class="title">选择接收人</text>
					<u-icon name="close" size="26" color="#888" @click="closeReceiverPopup" />
				</view>
				<view class="rps-body">
					<view class="rps-left">
						<scroll-view scroll-y class="dept-scroll">
							<view v-for="node in deptFlat" :key="node.id" class="dept-row"
								:class="{ active: node.id === currentDeptId }"
								:style="{ paddingLeft: (node.depth * 20) + 'rpx' }">
								<text class="toggle" v-if="node.hasChildren" @click.stop="toggleDept(node)">{{
									node.expanded ? '-' : '+' }}</text>
								<text class="d-label" @click="selectDept(node)">{{ node.label }}</text>
							</view>
						</scroll-view>
					</view>
					<view class="rps-right">
						<view class="rps-tools">
							<u--input v-model="userKeyword" placeholder="搜索用户" size="mini" clearable
								@input="onUserKeywordInput" @clear="onUserKeywordCleared" />
						</view>
						<scroll-view scroll-y class="user-table-scroll">
							<view class="ut-head">
								<view class="cell sel"><u-checkbox :checked="isAllPageSelected"
										@change="toggleSelectAllPage" /></view>
								<view class="cell name">用户名</view>
								<view class="cell dept">部门</view>
							</view>
							<view class="ut-body">
								<view v-if="loadingUsers" class="ut-row" style="justify-content:center;color:#888;">
									加载中...</view>
								<view v-else v-for="u in userList" :key="u.id" class="ut-row">
									<view class="cell sel"><u-checkbox :checked="selectedUserIds.includes(u.id)"
											@click.stop @change="toggleSelectUser(u)" /></view>
									<view class="cell name" :title="u.name">{{ u.name }}</view>
									<view class="cell dept" :title="u.deptName">{{ u.deptName }}</view>
								</view>
								<view v-if="!loadingUsers && userList.length === 0" class="empty">暂无数据</view>
							</view>
						</scroll-view>
					</view>
				</view>
				<view class="rps-ft">
					<u-button size="small" plain type="warning" @click="clearReceivers">清空</u-button>
					<u-button size="small" type="primary" color="#0A993B" @click="confirmReceivers">确定</u-button>
				</view>
			</view>
		</u-popup>
		<u-safe-bottom />
	</view>
</template>

<script>
import {
	deptTree,
	sylist,
	postnoticedetail,
	getnoticedetail,
	editnoticedetail,
	getjsr
} from '@/api/sylin/index.js'
import config from '@/config.js'

export default {
	data() {
		return {
			// 按后端字段定义初始化
			showbutt: false,
			form: {
				noticeId: '',
				title: '',
				noticeType: '',
				emergencyLevel: '',
				needReply: 'N',
				content: '',
				attachment: '',
				senderId: '',
				senderName: '',
				senderDeptId: '',
				senderDeptName: '',
				recipientIds: '',
				recipientDeptIds: '',
				recipientNames: ''
			},
			uploadedFiles: [],
			noticeTypeOptions: [],
			urgencyOptions: [],
			showTypePicker: false,
			showUrgencyPicker: false,
			showReceiverPicker: false,
			deptTree: [],
			deptFlat: [],
			currentDeptId: '',
			userList: [],
			userKeyword: '',
			selectedUserIds: [],
			nameCache: {}, // id -> 用户名
			userCache: {}, // id -> 原始用户对象
			loadingUsers: false,
			_requestDeptId: null,
			_searchDebounceTimer: null,
		}
	},
	onLoad(options) {
		if (options && options.id) {
			this.showbutt = true
			this.getgetnoticedetail(options.id)
		}
		this.loadDicts()
	},
	computed: {
		navbarHeight() {
			if (this.customNavbarHeight) return this.customNavbarHeight
			const info = uni.getSystemInfoSync()
			return info.statusBarHeight * 2 + 44 * 2
		},
		isAllPageSelected() { return this.userList.length > 0 && this.userList.every(u => this.selectedUserIds.includes(u.id)) }
	},
	methods: {
		async getgetnoticedetail(id) {
			const res = await getnoticedetail(id)
			console.log(res)
			// 合并到已存在的 this.form，避免直接替换导致响应式丢失
			if (res && res.data && typeof res.data === 'object') {
				Object.assign(this.form, res.data)
			}
			const res1 = await getjsr(id)
			console.log(res1)
			// 兼容不同后端返回结构，安全取 rows
			const rows = (res1 && (Array.isArray(res1.rows) ? res1.rows :
				(Array.isArray(res1.data) ? res1.data : (res1.data && Array.isArray(res1.data.rows) ? res1.data.rows : [])))) || []
			const names = rows.map(item => item.receiverName || item.receiver || item.name).filter(Boolean)
			// 使用 $set 确保在任何情况下都是响应式的
			this.$set(this.form, 'recipientNames', names.join(','))
			// 同时填充 recipientIds / recipientDeptIds 与本地缓存，保证编辑时校验通过并能在弹窗显示已选中项
			const ids = []
			const deptIds = []
			rows.forEach((item, idx) => {
				// 尝试从常见字段提取 id
				const id = item.userId || item.id || item.receiverId || ('r_' + idx)
				ids.push(id)
				// dept id 兼容提取
				const d = item.deptId || (item.dept && (item.dept.deptId || item.dept.id)) || ''
				if (d) deptIds.push(d)
				// 填充本地缓存
				this.nameCache[id] = item.receiverName || item.receiver || item.name || ('用户' + idx)
				this.userCache[id] = item
			})
			this.$set(this.form, 'recipientIds', ids.join(','))
			this.$set(this.form, 'recipientDeptIds', deptIds.join(','))
			// selectedUserIds 用来在弹窗中标记已选择的用户
			this.selectedUserIds = ids.slice()
			console.log('loaded recipients', this.form.recipientIds, this.form.recipientNames)
		},
		// 字典
		async loadDicts() {
			try {
				const nt = await (this.getDicts && this.getDicts('notice_type'))
				if (nt && Array.isArray(nt.data)) this.noticeTypeOptions = nt.data.map(d => ({ label: d.dictLabel, value: d.dictValue }))
				const ug = await (this.getDicts && this.getDicts('urgency'))
				if (ug && Array.isArray(ug.data)) this.urgencyOptions = ug.data.map(d => ({ label: d.dictLabel, value: d.dictValue }))
			} catch (e) { console.error('加载字典失败', e) }
		},
		getNoticeTypeLabel(v) { const f = this.noticeTypeOptions.find(i => i.value == v); return f ? f.label : '' },
		getUrgencyLabel(v) { const f = this.urgencyOptions.find(i => i.value == v); return f ? f.label : '' },
		onTypeConfirm(e) { const label = e.value[0]; const opt = this.noticeTypeOptions.find(o => o.label === label); if (opt) this.form.noticeType = opt.value; this.showTypePicker = false },
		onUrgencyConfirm(e) { const label = e.value[0]; const opt = this.urgencyOptions.find(o => o.label === label); if (opt) this.form.emergencyLevel = opt.value; this.showUrgencyPicker = false },

		// 接收人选择
		chooseReceivers() {
			if (!this.deptTree.length) { this.loadDeptTree(true); return }
			if (!this.currentDeptId && this.deptFlat.length) { this.currentDeptId = this.deptFlat[0].id; this.loadUsers() }
			this.showReceiverPicker = true
		},
		closeReceiverPopup() { this.showReceiverPicker = false },
		loadDeptTree(openAfter) {
			deptTree().then(res => {
				const data = Array.isArray(res.data) ? res.data : []
				data.forEach(r => r.expanded = true)
				this.deptTree = data
				this.rebuildDeptFlat()
				if (!this.currentDeptId && this.deptFlat.length) { this.currentDeptId = this.deptFlat[0].id; this.loadUsers() }
				if (openAfter) this.showReceiverPicker = true
			}).catch(err => console.error('获取部门树失败', err))
		},
		rebuildDeptFlat() { const walk = (nodes, depth = 0, out = []) => { nodes.forEach(n => { const has = n.children && n.children.length > 0; out.push({ id: n.id, label: n.label, depth, hasChildren: has, expanded: !!n.expanded }); if (has && n.expanded) walk(n.children, depth + 1, out) }); return out }; this.deptFlat = walk(this.deptTree) },
		toggleDept(node) { const toggle = (list) => { list.forEach(n => { if (n.id === node.id) { n.expanded = !n.expanded } else if (n.children) toggle(n.children) }) }; toggle(this.deptTree); this.rebuildDeptFlat() },
		async selectDept(node) { if (this.currentDeptId !== node.id) { this.currentDeptId = node.id; await this.loadUsers() } },
		async loadUsers() {
			if (!this.currentDeptId) return
			// 防抖：记录本次 deptId
			const deptId = this.currentDeptId
			this._requestDeptId = deptId
			this.loadingUsers = true
			try {
				// 固定 pageNum=1,pageSize=99999 按需求一次取全量
				const res = await sylist({ pageNum: 1, pageSize: 99999, deptId })
				// 兼容不同后端字段：rows / data / records
				let list = []
				if (res) {
					if (Array.isArray(res.rows)) list = res.rows
					else if (Array.isArray(res.data)) list = res.data
					else if (res.data && Array.isArray(res.data.rows)) list = res.data.rows
					else if (Array.isArray(res.records)) list = res.records
				}
				// 期望字段统一：id / name / nickName / deptName
				list = list.map((u, i) => {
					const id = u.userId || u.id || (deptId + '-' + i)
					return {
						id,
						name: u.userName || u.username || u.name || u.nickName || ('用户' + i),
						deptName: u.deptName || (u.dept && (u.dept.deptName || u.dept.name)) || deptId,
						_raw: u
					}
				})
				// 若关键字搜索（在全量上过滤）
				if (this.userKeyword) { list = list.filter(u => u.name.includes(this.userKeyword) || (u.nickName && u.nickName.includes(this.userKeyword))) }
				// 如果期间已切换部门，放弃这次结果
				if (this._requestDeptId !== this.currentDeptId) return
				// 不分页，直接全部展示
				this.userList = list
				this.userList.forEach(u => { this.nameCache[u.id] = u.name; this.userCache[u.id] = u })
			} catch (e) {
				console.error('加载用户失败', e)
				if (this._requestDeptId === this.currentDeptId) {
					this.userList = []
					uni.showToast({ title: '用户加载失败', icon: 'none' })
				}
			} finally {
				if (this._requestDeptId === this.currentDeptId) this.loadingUsers = false
			}
		},
		onUserSearch() { this.loadUsers() },
		onUserKeywordInput() {
			if (this._searchDebounceTimer) clearTimeout(this._searchDebounceTimer)
			this._searchDebounceTimer = setTimeout(() => { this.onUserSearch() }, 300)
		},
		onUserKeywordCleared() { this.userKeyword = ''; this.onUserSearch() },
		toggleSelectUser(u) {
			const id = u.id || u
			if (u.name && !this.nameCache[id]) this.nameCache[id] = u.name
			if (u._raw && !this.userCache[id]) this.userCache[id] = u._raw
			const i = this.selectedUserIds.indexOf(id)
			if (i > -1) this.selectedUserIds.splice(i, 1)
			else this.selectedUserIds.push(id)
		},
		toggleSelectAllPage() { if (this.isAllPageSelected) { this.userList.forEach(u => { const i = this.selectedUserIds.indexOf(u.id); if (i > -1) this.selectedUserIds.splice(i, 1) }) } else { this.userList.forEach(u => { if (!this.selectedUserIds.includes(u.id)) this.selectedUserIds.push(u.id) }) } },
		clearReceivers() {
			this.selectedUserIds = []
			this.form.recipientIds = ''
			this.form.recipientNames = ''
			this.form.recipientDeptIds = ''
		},
		confirmReceivers() {
			const ids = this.selectedUserIds
			const names = ids.map(id => this.nameCache[id] || id)
			const deptIds = ids.map(id => {
				const raw = this.userCache[id]
				if (raw) {
					return raw.deptId || (raw.dept && (raw.dept.deptId || raw.dept.id)) || ''
				}
				return ''
			}).filter(Boolean)
			this.form.recipientIds = ids.join(',')
			this.form.recipientNames = names.join(',')
			this.form.recipientDeptIds = deptIds.join(',')
			this.closeReceiverPopup()
		},

		// 附件 (占位)
		handleUpload() {
			// if (this.$refs.lsjUploadRef && this.$refs.lsjUploadRef.choose) 
			// this.$refs.lsjUploadRef.choose()
			this.$refs.lsjUploadRef.chooseFile({
				count: 5, // 最多选择5个文件
				size: 10, // 单个文件最大10MB
				multiple: true, // 允许多选
				formats: 'pdf,doc,docx,xls,xlsx,ppt,pptx,txt,jpg,jpeg,png,gif', // 支持常见文档和图片格式
				success: (files) => {
					console.log('选择的文件:', files)
					// 将新选择的文件添加到现有文件列表
					this.uploadedFiles = [...this.uploadedFiles, ...files]
					// 自动上传文件
					this.autoUploadFiles(files)
				},
				fail: (error) => {
					console.error('选择文件失败:', error)
					uni.showToast({
						title: '选择文件失败',
						icon: 'none'
					})
				}
			})
		},
		// 自动上传文件
		autoUploadFiles(newFiles) {
			newFiles.forEach(file => {
				this.uploadFile(file)
			})
		},
		uploadFile(file) {
			// 文件上传接口 - 使用通知附件上传接口
			const uploadUrl = `${config.baseUrl}/file/upload`

			this.$refs.lsjUploadRef.upload({
				file: file,
				url: uploadUrl,
				name: 'file',
				method: 'post',
				header: {
					Authorization: 'Bearer ' + uni.getStorageSync('App-Token')
				},
				formData: {
					// 额外的表单数据
				},
				onprogress: (e) => {
					// 找到对应的文件并更新状态
					const fileIndex = this.uploadedFiles.findIndex(f => f === file)
					if (fileIndex > -1) {
						this.$set(this.uploadedFiles[fileIndex], 'status', 'progress')
						this.$set(this.uploadedFiles[fileIndex], 'progress', e.progress || 0)
					}
					console.log('上传进度:', e)
				},
				success: (e) => {
					// 找到对应的文件并更新状态
					const fileIndex = this.uploadedFiles.findIndex(f => f === file)
					if (fileIndex > -1) {
						this.$set(this.uploadedFiles[fileIndex], 'status', 'success')
						this.$set(this.uploadedFiles[fileIndex], 'url', e.data.url || e.data.data?.url)
						this.$set(this.uploadedFiles[fileIndex], 'responseText', e.data)
					}
					console.log('上传成功:', e)
					uni.showToast({
						title: '文件上传成功',
						icon: 'success'
					})
				},
				fail: (e) => {
					// 找到对应的文件并更新状态
					const fileIndex = this.uploadedFiles.findIndex(f => f === file)
					if (fileIndex > -1) {
						this.$set(this.uploadedFiles[fileIndex], 'status', 'fail')
					}
					console.error('上传失败:', e)
					uni.showToast({
						title: '文件上传失败',
						icon: 'none'
					})
				}
			})
		},
		removeFile(i) { this.uploadedFiles.splice(i, 1) },
		
		// 格式化文件大小
		formatFileSize(bytes) {
			if (bytes === 0) return '0 B'
			const k = 1024
			const sizes = ['B', 'KB', 'MB', 'GB']
			const i = Math.floor(Math.log(bytes) / Math.log(k))
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
		},

		// 提交
		async onPublish() {
			if (!this.form.title) { uni.showToast({ title: '请输入标题', icon: 'none' }); return }
			if (!this.form.noticeType) { uni.showToast({ title: '请选择通知类型', icon: 'none' }); return }
			if (!this.form.recipientIds) { uni.showToast({ title: '请选择接收人', icon: 'none' }); return }
			// 构建附件字段（若已上传列表有路径）
			if (this.uploadedFiles.length) { this.form.attachment = this.uploadedFiles.filter(f => f.url).map(f => f.url).join(',') }
			if (!this.showbutt) {
				const res = await postnoticedetail(this.form)
				console.log(res)
				uni.showToast({ title: '已发布', icon: 'success' })
				uni.navigateBack()
			} else {
				const res = await editnoticedetail(this.form)
				console.log(res)
				uni.showToast({ title: '已修改', icon: 'success' })
				uni.navigateBack()
			}

		},
		onSaveDraft() {
			if (this.uploadedFiles.length) { this.form.attachment = this.uploadedFiles.filter(f => f.url).map(f => f.url).join(',') }
			uni.showToast({ title: '草稿已保存', icon: 'success' })
			uni.navigateBack()
		},
		onReset() {
			this.form = {
				noticeId: '', title: '', noticeType: '', emergencyLevel: '', needReply: 'N', content: '', attachment: '', senderId: '', senderName: '', senderDeptId: '', senderDeptName: '', recipientIds: '', recipientDeptIds: '', recipientNames: ''
			}
			this.uploadedFiles = []
			this.selectedUserIds = []
			this.nameCache = {}
			this.userCache = {}
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 1;
}

.page-wrap {
	background: #f5fef8;
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	box-sizing: border-box;
}

.form-scroll {
	flex: 1;
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
	box-sizing: border-box;
	padding-bottom: 140rpx;
	/* 预留底部按钮高度避免内容被挡 */
}


.form-card {
	background: #fff;
	border-radius: 20rpx;
	padding: 28rpx;
	margin: 24rpx 24rpx 0;
	box-shadow: 0 4rpx 14rpx rgba(0, 0, 0, .05);
}

.fc-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #0A993B;
	margin-bottom: 20rpx;
	position: relative;
	padding-left: 20rpx;
}

.fc-title:before {
	content: '';
	position: absolute;
	left: 0;
	top: 8rpx;
	width: 8rpx;
	height: 32rpx;
	background: #0A993B;
	border-radius: 4rpx;
}

.form-item {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-bottom: 24rpx;
}

.form-item.no-flex {
	align-items: flex-start;
	flex-direction: column;
}

.label {
	width: 140rpx;
	font-size: 26rpx;
	color: #333;
	flex-shrink: 0;
}

.picker-field {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: #f2fdf4;
	border: 1rpx solid #b6e7c9;
	padding: 18rpx 24rpx;
	border-radius: 14rpx;
	color: #0A6B2A;
	font-size: 26rpx;
}

.receiver-box {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.tag-list {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
}

.tag {
	background: #0A993B;
	color: #fff;
	padding: 10rpx 18rpx;
	border-radius: 100rpx;
	font-size: 22rpx;
}

.upload-list {
	margin-top: 10rpx;
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.upload-item {
	background: #f6fff8;
	border: 1rpx solid #c8efd7;
	border-radius: 14rpx;
	padding: 16rpx 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.u-left {
	display: flex;
	align-items: center;
	gap: 16rpx;
	color: #333;
	font-size: 24rpx;
}

.u-name {
	max-width: 260rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.u-size {
	color: #888;
	font-size: 22rpx;
}

.u-right {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.ok {
	color: #0A993B;
	font-size: 22rpx;
}

.ing {
	color: #f4b400;
	font-size: 22rpx;
}

.fail {
	color: #ff4d4f;
	font-size: 22rpx;
}

.btn-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx 24rpx env(safe-area-inset-bottom);
	display: flex;
	gap: 24rpx;
	box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, .06);
	background: #fff;
	z-index: 20;
	box-sizing: border-box;
}

.btn-bar .u-button {
	flex: 1;
}

.bottom-space {
	height: 40rpx;
}

/* ===== 新版接收人选择弹窗统一样式 ===== */
/* 全屏近似高度，保证内容完整显示；超高设备留出顶部 6vh 空间 */
.receiver-popup-simple {
	height: 92vh;
	max-height: 100vh;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	padding-bottom: env(safe-area-inset-bottom);
}

.receiver-popup-simple .rps-hd {
	flex-shrink: 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 28rpx;
	border-bottom: 1rpx solid #eee;
	background: #fff;
}

.receiver-popup-simple .title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.rps-body {
	flex: 1;
	min-height: 0;
	display: flex;
	overflow: hidden;
}

/* 左侧稍微缩窄，给右侧更多空间 */
.rps-left {
	width: 30%;
	max-width: 280rpx;
	min-width: 220rpx;
	border-right: 1rpx solid #eee;
	display: flex;
	flex-direction: column;
	background: #fafafa;
}

.dept-scroll {
	flex: 1;
	min-height: 0;
	height: 100%;
}

.dept-row {
	display: flex;
	align-items: center;
	gap: 12rpx;
	font-size: 24rpx;
	line-height: 44rpx;
	padding: 0 16rpx;
	cursor: pointer;
}

.dept-row.active {
	background: #e9f8ee;
	color: #0A993B;
	font-weight: 600;
}

.dept-row .toggle {
	width: 36rpx;
	text-align: center;
	color: #0A993B;
	font-weight: 600;
}

.rps-right {
	flex: 1;
	display: flex;
	flex-direction: column;
	min-width: 0;
}

.rps-tools {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 12rpx 16rpx;
	border-bottom: 1rpx solid #f0f0f0;
	background: #fff;
}

.user-table-scroll {
	flex: 1;
	min-height: 0;
}

.ut-head {
	display: flex;
	background: #f5f7fa;
	font-weight: 600;
	border-bottom: 1rpx solid #e6e6e6;
	position: sticky;
	top: 0;
	z-index: 2;
}

.ut-body {
	display: block;
}

.ut-row {
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #f1f1f1;
	min-height: 70rpx;
	background: #fff;
}

.ut-row:nth-child(2n) {
	background: #fcfdfc;
}

.ut-row:hover {
	background: #f2fbf5;
}

.cell {
	padding: 8rpx 12rpx;
	box-sizing: border-box;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	font-size: 24rpx;
	display: flex;
	align-items: center;
}

.cell.sel {
	width: 60rpx;
	flex: 0 0 60rpx;
	justify-content: center;
}

/* 调整列宽自适应；移除昵称列后收窄用户名列 */
.cell.name {
	flex: 0 0 180rpx;
}

.cell.dept {
	flex: 1;
	min-width: 0;
}

.empty {
	padding: 40rpx 0;
	text-align: center;
	color: #999;
	font-size: 24rpx;
}

.rps-ft {
	padding: 16rpx 20rpx;
	display: flex;
	gap: 24rpx;
	border-top: 1rpx solid #eee;
	background: #fff;
}

/* 滚动条微调（可选） */
.user-table-scroll ::-webkit-scrollbar {
	width: 8rpx;
}

.user-table-scroll ::-webkit-scrollbar-thumb {
	background: #c8e9d4;
	border-radius: 4rpx;
}
</style>